package priv.wangy.micro.common.dstb.autoId;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.stereotype.Component;
import priv.wangy.micro.common.config.appnode.AppNodeConfig;
import priv.wangy.micro.common.config.appnode.AppNodeProperties;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author zhangjq
 * @since 2023-10-16
 */
@Component
public class DstbAutoIdFactory {

    private final AppNodeProperties properties;

    private final BeanFactory beanFactory;

    private final Map<String, AutoIdGenerator> generatorMap = new HashMap<>();

    private static final String AUTO_ID = "ID";

    public DstbAutoIdFactory(AppNodeConfig config, BeanFactory beanFactory) {
        this.properties = config.getAppNodeProperties();
        this.beanFactory = beanFactory;
        generatorMap.put(AUTO_ID, beanFactory.getBean(AutoIdGenerator.class));
    }

    private AutoIdGenerator getGenerator(String key) {
        AutoIdGenerator generator = generatorMap.get(key);
        if (Objects.isNull(generator)) {
            generator = this.beanFactory.getBean(AutoIdGenerator.class);
            generatorMap.put(key, generator);
        }
        return generator;
    }

    public String getAutoNo(String key, int n) {
        return this.getGenerator(key).simpleNext(n);
    }

    public String getAutoId(String prefix, String key, int n) {
        return prefix + this.getGenerator(key).next(n);
    }

    public String getAutoId(String prefix) {
        return getAutoId(prefix, AUTO_ID, 4);
    }

    public String getAutoId() {
        return getAutoId(String.format("%02x%02x", this.properties.getAppIndex(), this.properties.getNodeIndex()), AUTO_ID, 4);
    }

    public void clear() {
        generatorMap.forEach((key, generator) -> generator.clear());
    }
}
